(function () {
	angular
	.module('ydApp.chat')
	.config(function ($stateProvider) {
		$stateProvider.state('post-chat', {
			cache: false,
			url: '/post-chat',
			controller: "postChatCtrl",
			templateUrl: 'views/chats/post-chat.html'
		});
		
	})
	.controller("postChatCtrl", postChatCtrl);

	function postChatCtrl ($scope, xhr, localStore, reverseFilter, $timeout, $anchorScroll, chatInterval) {
		var vm = $scope.vm = {};
		vm.chatId = '';
		vm.user = localStore.get('user');
		vm.queryStartTime = "";
		vm.queryEndTime = "";
		vm.msgs = [];
		vm.loadMsg = function() {
			return xhr.get('HealthInquiry/com/callMsg/callMsgs', {
				callId: vm.chatId,
				userId: vm.user.id,
				queryEndTime: vm.queryStartTime,
				sortField: 'sendTime',
				sortOrder: 'desc',
				pageSize: 10,
			}).then(function (res) {
				if (res.successful) {
					if (res.data.length > 0) {
						vm.queryStartTime = res.data[0].queryStartTimeString;
						vm.queryEndTime = res.data[0].queryEndTimeString;
						var msgs = reverseFilter(res.data);
						vm.msgs = msgs.concat(vm.msgs);
					}
					if (vm.msgs.length == 0) {
						vm.message = "  ";
						vm.sendMsg(0, '请详细描述您的症状、疾病和身体情况，延陵医道会为您提供相关帮助');
					}
				}
			}).finally(function () {
				$scope.$broadcast('scroll.refreshComplete');
			})
		};
		function startInteval() {
			chatInterval.interval = setInterval(function () {
				xhr.get('HealthInquiry/com/callMsg/callMsgs', {
					callId: vm.chatId,
					userId: vm.user.id,
					queryStartTime: vm.queryEndTime,
					sortField: 'sendTime',
					sortOrder: 'desc',
					pageSize: 10,
				}).then(function (res) {
					if (res.successful) {
						for (var i = 0; i < res.data.length; i++) {
							var check = true;
							for (var j = 0; j < vm.msgs.length; j++) {
								if (vm.msgs[j].id == res.data[i].id) {
									check = false;
									break;
								}
							}
							if(check){
								vm.msgs.push(res.data[i]);
								messageToBottom();
							}
						}
					}
				}, function (error) {
					clearInterval(chatInterval.interval);
					popup.confirm('加载失败'+error+'?', '重新加载', '返回').then(function (ok) {
						if (ok) {
							startInteval();
						} else {
							$ionicHistory.goBack();
						}
					});
				})
			}, 1000)
		}
		startInteval();
		var ispost = false;
		vm.sendMsg = function (userId, message) {
			if (!vm.message || ispost) {
				return;
			}
			ispost = true;
			xhr.get('HealthInquiry/com/callMsg/sendMsg', {
				callId: vm.chatId,
				userId: userId || vm.user.id,
				content: message || vm.message,
				msgType: 0
			}).then(function (res) {
				vm.msgs.push(res.data);
				vm.message = "";
				messageToBottom();
			}).finally(function () {
				ispost = false;
			});
		};
		vm.keyup = function ($event) {
			if ($event.keyCode == 13) {
				vm.sendMsg(vm.user.id, vm.message);
			}
		}
		function messageToBottom() {
            $timeout(function () {
                $anchorScroll("msg-bottom", 0);
            }, 0);
        }
		(function (startCall) {
			startCall().then(function () {
				vm.loadMsg().then(function () {
					messageToBottom();
				});
			});
		})(function () {
			return xhr.get('HealthInquiry/com/call/startDutyCall', {
				fromUser: vm.user.id
			}).then(function (res) {
				if (res.successful) {
					vm.chatId = res.data.id;
					vm.docHead = res.data.toUserHeadImgUrl;
					vm.head = res.data.fromUserHeadImgUrl;
					vm.topTitle = res.resultMsg;
				}
			});
		});

		
	}
})();